<template>
  <div>
    <ZWDrawer ref="zwRef" @submit="save" @close="close" @cancel="cancel">
      <div class="contents">
        <!-- <div class="toggleType" v-if="drawerData.controlType === 'create'">
          <div class="toggleBtn" @click="toggleType">
            <el-icon>
              <Switch />
            </el-icon>
            切换客户类型
          </div>
        </div> -->

        <el-form :model="form" ref="ruleFormRef" label-width="auto">
          <div class="form-title">企业信息</div>
          <el-form-item :label="item.attr_name" v-for="(item, index) in customCropAttr" :required="item.is_required == 2">
            <el-input v-model="item.current_val" :placeholder="'请输入' + item.attr_name" v-if="item.attr_type == 'textbox'" :disabled="drawerData.controlType == 'look'" />
            <!-- <el-input v-model="item.current_val" :placeholder="'请输入' + item.attr_name"
              v-if="item.attr_type == 'textbox'" @blur="valiateid(index, true, item.is_required)" /> -->
            <el-input v-model="item.current_val" :placeholder="'请输入' + item.attr_name" v-if="item.attr_type == 'mobile'" indeterminate @blur="valiateMobile(index, true, item.is_required)" :disabled="drawerData.controlType == 'look'" />
            <el-input :disabled="drawerData.controlType == 'look'" v-if="item.attr_type == 'email'" v-model="item.current_val" :placeholder="`请输入${item.attr_name}`"></el-input>
            <el-input :disabled="drawerData.controlType == 'look'" v-model="item.current_val" v-if="item.attr_type == 'textarea'" type="textarea" :placeholder="`请输入${item.attr_name}`"></el-input>

            <el-checkbox-group v-model="item.current_val" v-if="item.attr_type == 'muti_select'" :disabled="drawerData.controlType == 'look'">
              <el-checkbox v-for="items in item.attr_val" :label="items.key">{{ items.val }}</el-checkbox>
            </el-checkbox-group>
            <el-select v-model="item.current_val" v-if="item.attr_type == 'select'" :placeholder="'请选择' + item.attr_name" :disabled="drawerData.controlType == 'look'" >
              <el-option v-for="items in item.attr_val" :value="items.key" :label="items.val">{{ items.val }} </el-option>
            </el-select>
            <CascaderItem v-if="item.attr_type == 'pca'" :itemValue="item" :isDisabled="drawerData.controlType" />
            <!-- <el-input v-model="item.current_val" :placeholder="'请输入' + item.attr_name" v-if="item.attr_type == 'pca'" :disabled="drawerData.controlType == 'look'" /> -->

            <!-- <el-cascader :disabled="drawerData.controlType == 'look'" v-if="item.attr_type == 'pca'"
              v-model="item.current_val" :options="item.attr_val" :placeholder="`请选填${item.attr_name}`">
            </el-cascader> -->

            <el-date-picker style="width: 100%" value-format="YYYY-MM-DD" :disabled="drawerData.controlType == 'look'" v-if="item.attr_type == 'date'" v-model="item.current_val" type="date" :placeholder="`请输入${item.attr_name}`"></el-date-picker>

            <div :class="`upload-content ${drawerData.controlType == 'look' ? 'noEdit' : ''}`" v-if="item.attr_type == 'picture'">
              <el-upload
                action="none"
                v-if="!item.current_val"
                @click="getUploadKey(index, true)"
                :on-change="beforeAvatarUpload"
                accept=".jpg,.jpeg,.png,.JPG,.JPEG"
                :show-file-list="false"
                :limit="1"
                :auto-upload="false"
                :disabled="drawerData.controlType == 'look'"
              >
                <div class="upload-box">
                  <img src="@/assets/image/content/add-icon.png" alt="" />
                  <div>点击上传</div>
                </div>
              </el-upload>
              <div class="upload-file-box" v-else>
                <el-image style="width: 100%; height: 100%" :src="item.current_val" fit="cover" />
                <el-icon @click="delFile(index, true)" class="del">
                  <Delete />
                </el-icon>
              </div>
            </div>
          </el-form-item>

          <div class="form-title">客户信息</div>
          <el-form-item label="客户公海" required>
            <el-select v-model="form.seas_id" placeholder="请选择客户公海" :disabled="drawerData.controlType == 'look'">
              <el-option v-for="(item, index) in seaids" :value="item.id" :label="item.name" :key="item.id">{{ item.name }}</el-option>
            </el-select>
          </el-form-item>

          <el-form-item :label="item.attr_name" v-for="(item, index) in customAttr" :key="item.id" :required="item.is_required == 2">
            <CascaderItem v-if="item.attr_type == 'pca'" :itemValue="item" :isDisabled="drawerData.controlType" />
            <el-input v-model="item.current_val" :placeholder="'请输入' + item.attr_name" v-if="item.attr_type == 'textbox'" :disabled="drawerData.controlType == 'look'" />
            <!-- <el-input v-model="item.current_val" :placeholder="'请输入' + item.attr_name"
              v-if="item.attr_type == 'textbox'" @blur="valiateid(index, false, item.is_required)" /> -->
            <el-input v-model="item.current_val" :placeholder="'请输入' + item.attr_name" v-if="item.attr_type == 'mobile'" indeterminate @blur="valiateMobile(index, false, item.is_required)" :disabled="drawerData.controlType == 'look'" />
            <el-input :disabled="drawerData.controlType == 'look'" v-if="item.attr_type == 'email'" v-model="item.current_val" :placeholder="`请输入${item.attr_name}`"></el-input>
            <el-input :disabled="drawerData.controlType == 'look'" v-model="item.current_val" v-if="item.attr_type == 'textarea'" type="textarea" :placeholder="`请输入${item.attr_name}`"></el-input>
            <el-checkbox-group v-model="item.current_val" v-if="item.attr_type == 'muti_select'" :disabled="drawerData.controlType == 'look'">
              <el-checkbox v-for="items in item.attr_val" :label="items.key" :key="items.id">{{ items.val }}</el-checkbox>
            </el-checkbox-group>
            <el-select v-model="item.current_val" v-if="item.attr_type == 'select'" :placeholder="'请选择' + item.attr_name" :disabled="drawerData.controlType == 'look'" @click="getSource(index)">
              <el-option v-for="items in item.attr_val" :value="items.key" :key="items.id" :label="items.val">{{ items.val }} </el-option>
            </el-select>

            <el-date-picker style="width: 100%" value-format="YYYY-MM-DD" :disabled="drawerData.controlType == 'look'" v-if="item.attr_type == 'date'" v-model="item.current_val" type="date" :placeholder="`请输入${item.attr_name}`"></el-date-picker>

            <div :class="`upload-content ${drawerData.controlType == 'look' ? 'noEdit' : ''}`" v-if="item.attr_type == 'picture'">
              <el-upload
                action="none"
                v-if="!item.current_val"
                @click="getUploadKey(index, false)"
                :on-change="beforeAvatarUpload"
                accept=".jpg,.jpeg,.png,.JPG,.JPEG"
                :show-file-list="false"
                :limit="1"
                :auto-upload="false"
                :disabled="drawerData.controlType == 'look'"
              >
                <div class="upload-box">
                  <img src="@/assets/image/content/add-icon.png" alt="" />
                  <div>点击上传</div>
                </div>
              </el-upload>
              <div class="upload-file-box" v-else>
                <el-image style="width: 100%; height: 100%" :src="item.current_val" fit="cover" />
                <el-icon @click="delFile(index, false)" class="del">
                  <Delete />
                </el-icon>
              </div>
            </div>
          </el-form-item>

          <el-form-item label="客户阶段" required>
            <el-select v-model="form.grade_id" placeholder="请选择客户阶段" :disabled="drawerData.controlType == 'look'">
              <el-option v-for="(item, index) in levelid" :value="item.id" :key="item.id" :label="item.name">{{ item.name }} </el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="客户来源" required>
            <el-select v-model="form.source_id" placeholder="请选择客户来源" :disabled="drawerData.controlType == 'look'">
              <el-option v-for="(item, index) in sourceid" :value="item.id" :key="item.id" :label="item.name">{{ item.name }} </el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item label="归属员工" required>
            <select-depart v-model="form.belong_work_user_id" :creators="form.belong_work_user_id_creators" @change="changeBelongWorkUser"  :multiple="false" :disabled="drawerData.controlType == 'look'" />
          </el-form-item>

          <el-form-item label="协助员工">
            <select-depart v-model="form.assist_ids" :creators="form.assist_ids_creators" multiple  @change="changeAssist" :disabled="drawerData.controlType == 'look'" />
          </el-form-item>
        </el-form>
        <div class="form-title">联系人信息</div>
        <div class="contact-item" v-for="(item, index) in contactsForms" :key="item.id">
          <div class="title">
            <span>联系人{{ index + 1 }}</span>
            <el-icon class="del" :class="{ look: drawerData.controlType == 'look' }" :size="size" :color="color" @click="deleteContact(index)">
              <Delete />
            </el-icon>
          </div>
          <el-form :model="item" label-width="auto">
            <el-form-item label="姓名">
              <el-input v-model="item.name" :disabled="drawerData.controlType == 'look'" />
            </el-form-item>
            <el-form-item label="手机号">
              <el-input v-model="item.mobile" :disabled="drawerData.controlType == 'look'" />
            </el-form-item>
          </el-form>
        </div>
        <div class="add-contact" @click="addContact">添加联系人</div>
      </div>
    </ZWDrawer>

    <Dialog :appDialog="appDialogApply">
      <div class="dialog_content">该企业已存在，申请成为协助人？</div>
    </Dialog>

    <!-- <ZWDepart ref="DepartRef" @submit="getDepart" type="1" /> -->
  </div>
</template>
<script lang="ts" setup>
  import selectDepart from '@/components/customerCenter/selectDepart.vue'
  import { deepCopy } from '@/utils/helper'
  import { ref, reactive, watch, onMounted, onBeforeUnmount, getCurrentInstance, ComponentInternalInstance } from 'vue'
  import { ElForm, ElMessage, ElMessageBox, UploadProps, FormRules } from 'element-plus'
  import ZWDrawer from '@/components/ZWDrawer.vue'
  import ZWDepart from '@/components/ZWDepart.vue'
  import Dialog from '@/components/Dialog.vue'
  import { cpCnpre, saveCn } from '@/api/employe/employeetasks/taskmanage'

  import { getClubSource } from '@/api/customer/clubManage/commonSea'
  import { stageList } from '@/view/customer/manage/configure/api'
  import CascaderItem from '@/components/customerCenter/CascaderItem.vue'
  import { seaList, applyCompanyHelper, getCompanyCustomerForm, getCompanyCustomerDetail, addCompanyCustomer, aditCompanyCustomer } from '@/api/customerCenter/customerSea'

  import { uploadFile2 } from '@/api/common'
  import { getSetionId } from '@/utils/utils'

  type FormInstance = InstanceType<typeof ElForm>
  const ruleFormRef: any = ref<FormInstance>()

  const {
    appContext: {
      config: { globalProperties }
    }
  } = <ComponentInternalInstance>getCurrentInstance()

  onMounted(() => {
    globalProperties.$bus.on('openAddCustomerCompany', () => {
      updateVisible(true)
    })
  })
  onBeforeUnmount(() => {
    globalProperties.$bus.off('openAddCustomerCompany')
  })

  type Props = {
    modelValue: boolean
    row_id: string
    sourceArr: []
  }
  const props = defineProps<Props>()
  const emit = defineEmits(['close', 'submit', 'update:modelValue'])
  const updateVisible = (flag: boolean): void => {
    emit('update:modelValue', flag)
  }

  const drawerData = ref({
    title: '添加企业客户',
    direction: 'rtl',
    userInfo: {},
    controlType: 'create',
    seas_id: 0
  })

  const cust_id = ref<any>(0)
  const cancelHandel = () => {
    appDialogApply.visible = false
  }
  const submitHandel = () => {
    applyCompanyHelper({ cust_id: cust_id.value }).then((res: any) => {
      console.log('res - -  ', res)
      appDialogApply.visible = false
      zwRef.value.drawer = false
      emit('submit')
    })
  }
  const appDialogApply = reactive({
    visible: false,
    title: '申请协助人',
    width: '500px',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '申请协助人'
  })

  const zwRef = ref(null)
  const DepartRef = ref(null)
  const creators = ref([])
  let form = reactive({
    seas_id: '',
    grade_id: '',
    source_id: '',
    belong_work_user_id: [],
    assist_ids: [],
    belong_work_user_id_creators: [],
    assist_ids_creators: []
  })

  let contactsForms = reactive<any>([
    {
      name: '',
      mobile: ''
    }
  ])

  const imgProps = ref([]) // 自定义图片prop

  const contactsFormRules = reactive<FormRules>({
    name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' }]
  })

  let customCropAttr = reactive<any>([])
  let customAttr = reactive<any>([])

  const getDetail = () => {
    if (drawerData.value.controlType === 'create') {
      cpCnpre({ id: drawerData.value.seas_id }).then((res: any) => {
        console.log('转化为企业客户');
        const { company_attr, cust_attr } = res
        customCropAttr.splice(0)
        customAttr.splice(0)

        let ind: number = 0
        let trans = cust_attr.find((item: any, index: number) => {
          if (item.attr_name == '客户来源') {
            ind = index
            return true
          } else {
            return false
          }
        })
        if (trans) {
          let arr = props.sourceArr.map((it: any) => ({
            ...it,
            key: it.id || '',
            val: it.name || ''
          }))
          arr.shift()
          console.log(arr, '客户来源2222')
          trans.attr_val = arr
          cust_attr.splice(ind, 1, trans)
        }
        customCropAttr.push(...company_attr)
        customAttr.push(...cust_attr)
        initSelectDefaultVal()
      })
    } else {
      cpCnpre({ id: drawerData.value.seas_id }).then((res) => {
      
        
        for (let key in res) {
          if (key != 'custom_attr' && key != 'custom_crop_attr') {
            form[key] = res[key]
          }
        }
        const { custom_attr, custom_crop_attr, contacts_info: contacts_info = [], belong_work_user_id: belong_work_user_id = [], assist_ids: assist_ids = [] } = res
        if (belong_work_user_id?.length) {
          form.belong_work_user_id = belong_work_user_id?.map((ite) => ite.id)
          form.belong_work_user_id_creators = belong_work_user_id
        }
        if (assist_ids?.length) {
          form.assist_ids = assist_ids?.map((ite) => ite.id)
          form.assist_ids_creators = assist_ids
        }
        contactsForms.splice(0)
        if (contacts_info?.length) {
          if (drawerData.value.userInfo?.contact?.length) {
            const contacts = drawerData.value.userInfo.contact.map((item) => {
              return {
                id: item.id,
                name: item.name,
                mobile: item.mobile
              }
            })

            contactsForms.push(...contacts)
          }
        }
        let ind = 0
        let trans = custom_attr.find((item: any, index: number) => {
          if (item.attr_name == '客户来源') {
            ind = index
            return true
          } else {
            return false
          }
        })
        if (trans) {
          trans.current_val = Number(trans.current_val)
          let arr = props.sourceArr.map((it: any) => ({
            ...it,
            key: it.id || '',
            val: it.name || ''
          }))
          arr.shift()
          console.log(arr, '客户来源2222')
          trans.attr_val = arr
          custom_attr.splice(ind, 1, trans)
        }
        // if (custom_attr?.length) {
        //   contactsForms.splice(0)
        //   contactsForms.push(...custom_attr)
        // }

        customCropAttr.splice(0)
        customAttr.splice(0)
        customCropAttr.push(...custom_crop_attr)
        customAttr.push(...custom_attr)
        customCropAttr.forEach((item) => {
          if (item.attr_type == 'muti_select' && !item.current_val) {
            item.current_val = []
          }
          if (item.attr_type == 'pca') {
            if (item.current_val) {
              item.attr_val = [item.current_val.province_code.toString(), item.current_val.city_code.toString(), item.current_val?.area_code?.toString()]
              if (item.attr_val[2] == 0) {
                item.attr_val.pop()
              }
            } else {
              return
            }
          }
        })
        customAttr.forEach((item) => {
          if (item.attr_type == 'muti_select' && !item.current_val) {
            item.current_val = []
          }
          if (item.attr_type == 'pca') {
            if (item.current_val) {
              item.attr_val = [item.current_val.province_code.toString(), item.current_val.city_code.toString(), item.current_val?.area_code?.toString()]
              if (item.attr_val[2] == 0) {
                item.attr_val.pop()
              }
            } else {
              return
            }
          }
        })
      })
      console.log('form - -   ', form)
    }
  }
  const seaids = reactive<any>([]) //公海列表
  const levelid = reactive<any>([]) //客户等级列表
  const sourceid = ref([]) //客户来源

  // 切换客户类型
  const toggleType = () => {
    updateVisible(false)
    globalProperties.$bus.emit('openAddCustomerSelect')
  }

  //获取客户公海列表
  const getSeaList = () => {
    seaids.splice(0)
    seaList({ page: 1, page_size: 1000, name: '' }).then((res: any) => {
      seaids.push(...res.data)
    })
  }
  //获取客户等级
  const getLevelList = () => {
    levelid.splice(0)
    stageList({ page: 1, page_size: 99 }).then((res: any) => {
      levelid.push(...res)
    })
  }
  const getSourceList = () => {
  //获取客户来源
    sourceid.value = []
    getClubSource({ page: 1, page_size: 99 }).then((res: any) => {
      res.data.forEach((item) => {
        if (item.status == 1) {
          sourceid.value.push(item)
        }
      })
    })
  }
  //获取客户来源
  const getSource = (index:any)=>{
   if (customAttr[index].system_code == 'source' && !customAttr[index].attr_val?.length){
    getClubSource({ page: 1, page_size: 99 }).then((res: any) => {
      customAttr[index].attr_val =res.data.filter((item) => item.status == 1).map((item) => ({key: item.id, val: item.name}))
    })
   }
  }

  let nowUploadIndex = 0
  let nowUploadFlag = false
  const getUploadKey = (index: number, flag: boolean) => {
    nowUploadIndex = index
    nowUploadFlag = flag
  }

  // 上传图片的方法
  const uploadFun = (file: any, fileName: string, key: string) => {
    uploadFile2({
      file,
      fileName
    }).then((r: any) => {
      if (nowUploadFlag) {
        customCropAttr[nowUploadIndex].current_val = r.url
        // console.log(formData.value[nowUploadKey])
        // 验证图片上传
        if (imgProps.value.length > 0) {
          imgProps.value.forEach((item) => {
            ruleFormRef.value.validateField([item])
          })
        }
      } else {
        customAttr[nowUploadIndex].current_val = r.url
        // console.log(formData.value[nowUploadKey])
        // 验证图片上传
        if (imgProps.value.length > 0) {
          imgProps.value.forEach((item) => {
            ruleFormRef.value.validateField([item])
          })
        }
      }
    })
  }
  // 上传检验
  const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile: any, key: string) => {
    console.log(rawFile, key, 5556)
    if (!rawFile) {
      return
    }
    if (rawFile.size / 1024 / 1024 > 10) {
      ElMessage.error('上传图片大小不能超过10M')
      return false
    }
    uploadFun(rawFile.raw, rawFile.name, key)
  }

  //
  const delFile = (index: number, flag: boolean) => {
    if (flag) {
      customCropAttr[index].current_val = ''
    } else {
      customAttr[index].current_val = ''
    }
  }

  const valiateMobile = (index: number, flag: boolean, required?: number) => {
    let rex = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
    const current_val = flag ? customCropAttr[index].current_val : customAttr[index].current_val
    if (!rex.test(current_val)) {
      ElMessage.warning('请输入合法的手机号')
      return false
    } else {
      return true
    }
  }
  const valiateid = (index: number, flag: boolean, required?: number) => {
    let rex = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{16,}$/
    const attrs = flag ? customCropAttr[index] : customAttr[index]
    if (attrs.attr_name != '姓名' && required == 2) {
      if (!rex.test(attrs.current_val)) {
        ElMessage.warning(attrs.attr_name + '必须包含数字字母并且长度不能小于16位')
        return false
      } else {
        return true
      }
    } else {
      return true
    }
  }

  const save = () => {
    const validateCustomCropAttr = validateFun(customCropAttr, true)
    console.log('validateCustomCropAttr - - -  ', validateCustomCropAttr)
    if (validateCustomCropAttr) {
      const validateCustomAttr = validateFun(customAttr, false)
      if (validateCustomAttr && validateCustomForm()) {
        if (contactsForms.length) {
          if (contactsForms.some((item) => !item.name || !item.mobile)) {
            ElMessage.warning('请完善联系人信息')
            return
          }
        }
        if (drawerData.value.controlType === 'create') {
          const mobile = validateCustomAttr.find((item) => item.attr_name == '手机号')?.current_val || ''
          const corp_name = validateCustomCropAttr.find((item) => item.attr_name == '企业全称')?.current_val || ''
          const id = drawerData.value.seas_id
          const clue_source_id = form.source_id
          const clue_level_id = form.grade_id
          const clue_seas_id = form.seas_id
          const belong_staff = form.belong_work_user_id[0]
          const extraForm = {
            mobile,
            corp_name,
            clue_source_id,
            clue_level_id,
            clue_seas_id,
            id,
            belong_staff
          }
          const params = {
            ...extraForm,
            company_attr: validateCustomCropAttr,
            cust_attr: validateCustomAttr,
            company_contacts: contactsForms
          }
          console.log(params, '参数')

          saveCn(params).then((res) => {
            const { is_apply, cust_id: cust_id_ } = res
            if (is_apply == 1) {
              // 是否申请协助人    1 是    0 否    瞎卡拉卡
              cust_id.value = cust_id_
              appDialogApply.visible = true
            } else {
              emit('submit')
              ElMessage.success('保存成功')
              zwRef.value.drawer = false
            }
          })
        } else if (drawerData.value.controlType === 'edit') {
          const mobile = validateCustomAttr.find((item) => item.attr_name == '手机号')?.current_val || ''
          const corp_name = validateCustomCropAttr.find((item) => item.attr_name == '企业全称')?.current_val || ''
          const source_id = validateCustomCropAttr.find((item) => item.attr_name == '客户来源')?.current_val || ''
          const extraForm = { mobile, corp_name, source_id }
          const { belong_work_user_id: belong_work_user_id = [] } = form
          const params = {
            ...form,
            ...extraForm,
            belong_work_user_id: belong_work_user_id[0],
            custom_crop_attr: validateCustomCropAttr,
            custom_attr: validateCustomAttr,
            contacts_info: contactsForms,
            cust_id: drawerData.value.userInfo.id
          }
          aditCompanyCustomer(params).then((res) => {
            ElMessage.success('编辑成功')
            zwRef.value.drawer = false
            emit('submit')
          })
        }
      }
    }
  }

  const validateFun = (data: any, flag: boolean) => {
    if (!flag) {
    }
    try {
      data.forEach((item: any, index: number) => {
        if (!item.current_val && item.is_required == 2 && item.attr_type != 'muti_select') {
          ElMessage.warning(item.attr_name + '不能为空')
          throw new Error()
        } else if (item.attr_type == 'muti_select' && item.is_required == 2 && !item.current_val.length) {
          ElMessage.warning(item.attr_name + '不能为空')
          throw new Error()
        }
      })
    } catch (e) {
      return false
    }
    try {
      data.forEach((items: any, indexs: number) => {
        if (items.is_required == 2 && items.attr_type == 'mobile') {
          let flag2 = valiateMobile(indexs, flag)
          if (!flag2) {
            throw new Error()
          }
        } else if (items.is_required == 2 && items.attr_name != '姓名') {
          // let flag = valiateid(indexs, flag, 2)
          // if (!flag) {
          //   throw new Error()
          // }
        }
      })
    } catch (e) {
      return false
    }
    // data.forEach((item) => {
    //   delete item.attr_val
    //   delete item.is_required
    //   delete item.system_code
    // })

    return data
  }
  const changeBelongWorkUser = (ids: any, creators: any) => {
    if (ids?.length && form.assist_ids?.length && form.assist_ids.includes(ids[0])) {
      form.belong_work_user_id = []
      form.belong_work_user_id_creators = []
      ElMessage.error('归属员工不能是协助员工')
    }
  }

  const changeAssist = (ids: any, creators: any) => {
    if (form.belong_work_user_id?.length && ids?.length && ids.includes(form.belong_work_user_id[0])) {
      const index = ids.indexOf(form.belong_work_user_id[0])
      let assist_ids = deepCopy(form.assist_ids)
      let assist_ids_creators = deepCopy(creators)
      form.assist_ids = []
      form.assist_ids_creators = []
      assist_ids.splice(index, 1)
      assist_ids_creators.splice(index, 1)
      form.assist_ids = assist_ids
      form.assist_ids_creators = assist_ids_creators
      ElMessage.error('归属员工不能是协助员工')
    }
  }

  const validateCustomForm = (): boolean => {
    if (!form.seas_id) {
      ElMessage.warning('请选择公海')
      return false
    } else if (!form.grade_id) {
      ElMessage.warning('请选择客户阶段')
      return false
    } else if (!form.belong_work_user_id.length) {
      ElMessage.warning('请选择归属员工')
      return false
    } else {
      return true
    }
  }

  const cancel = () => {
    for (let key in form) {
      if (key != 'custom_attr' && key != 'seas_id') {
        form[key] = ''
      }
      initSelectDefaultVal()
    }
  }
  //数据
  const initSelectDefaultVal = () => {
    customCropAttr.forEach((item: any) => {
      if (item.attr_type == 'muti_select') {
        item.current_val = []
      } else {
        item.current_val = ''
      }
    })
    customAttr.forEach((item: any) => {
      if (item.attr_type == 'muti_select') {
        item.current_val = []
      } else {
        item.current_val = ''
      }
    })
  }

  const addContact = (): void => {
    if (contactsForms.length < 5) {
      const formItem: any = {
        name: '',
        mobile: ''
      }
      contactsForms.push(formItem)
    } else {
      ElMessage.warning('最多新建5个联系人')
    }
  }

  const deleteContact = (index: number): void => {
    if (drawerData.value.controlType !== 'look') {
      ElMessageBox.confirm('确定删除该联系人吗？', '注意！', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        contactsForms.splice(index, 1)
      })
    }
  }

  const close = () => {
    contactsForms.splice(0)
    addContact()
    emit('close')
  }
  watch(
    () => props.modelValue,
    (val) => {
      if (val) {
        form.grade_id = ''
        form.belong_work_user_id = []
        form.assist_ids = []
        form.belong_work_user_id_creators = []
        form.assist_ids_creators = []
        zwRef.value.resetMsg = '重置'
        zwRef.value.drawerMsg = '保存'
        zwRef.value.isResetShow = true
        if (drawerData.value.controlType === 'edit') {
          zwRef.value.isResetShow = false
          zwRef.value.title = '编辑企业客户'
        } else if (drawerData.value.controlType === 'look') {
          zwRef.value.isResetShow = false
          zwRef.value.title = '查看企业客户'
        } else {
          zwRef.value.title = '转化为企业客户'
        }
        getSourceList()
        getDetail()
        getLevelList()
        getSeaList()
        zwRef.value.drawer = true
        zwRef.value.width = '600px'
      } else {
        cancel()
        zwRef.value.drawer = false
      }
    }
  )

  defineExpose({
    drawerData
  })
</script>
<style scoped lang="scss">
  .contents {
    padding: 16px 0;

    .toggleType {
      margin-bottom: 6px;
      display: flex;
      justify-content: flex-end;
      align-items: center;

      .toggleBtn {
        font-size: 12px;
        color: #ff6b00;

        &:hover {
          cursor: pointer;
          color: #ffa046;
        }
      }
    }

    .form-title {
      height: 18px;
      line-height: 18px;
      font-weight: 700;
      border-left: 8px solid #ff6b00;
      padding-left: 6px;
      margin: 8px 0 24px;
    }

    .contact-item {
      border: 1px solid #eee;
      margin-bottom: 10px;
      padding: 10px 20px;
      box-sizing: border-box;

      .title {
        margin: 10px 0 16px;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .del {
          color: #ff6b00;

          &:hover {
            cursor: pointer;
          }
        }
        .look {
          color: #eee;
          cursor: not-allowed;
        }
      }
    }

    .add-contact {
      display: inline-block;
      margin-top: 10px;
      margin-bottom: 20px;
      line-height: 1;
      padding: 6px 24px;
      border-radius: 4px;
      color: #ff6b00;
      border: 1px solid #ff6b00;

      &:hover {
        cursor: pointer;
        background-color: #ff6b00;
        color: #fff;
      }
    }

    .el-form {
      .el-form-item {
        .staffs_item {
          margin-right: 6px;
        }
      }

      .upload-content {
        &.noEdit {
          pointer-events: none !important;

          .upload-box {
            background: lightgray;
            position: relative;

            &::after {
              content: '';
              width: 100%;
              height: 100%;
              background: lightgray;
              opacity: 0.6;
              position: absolute;
              top: 0;
              left: 0;
            }
          }
        }

        .upload-box {
          width: 110px;
          height: 110px;
          text-align: center;
          border-radius: 4px;
          background: #f8f8f8;
          border: 1px solid #eaeaea;
          box-sizing: border-box;
          padding-top: 28px;

          img {
            width: 20px;
            height: 20px;
          }

          div {
            width: 100%;
            line-height: 14px;
            font-size: 14px;
            font-family: STHeitiSC-Light, STHeitiSC;
            color: #ff6b00;
          }
        }

        .upload-file-box {
          position: relative;
          width: 110px;
          height: 110px;
          border-radius: 4px;
          border: 1px solid #eaeaea;
          overflow: hidden;

          .del {
            position: absolute;
            width: 15px;
            height: 15px;
            top: 5px;
            right: 5px;
            color: #e4e7ed;
          }
        }

        .upload-desc {
          font-size: 14px;
          font-family: STHeitiSC-Light, STHeitiSC;
          font-weight: 300;
          color: #969696;
          padding-top: 10px;

          span {
            color: #ff6b00;
            cursor: pointer;
          }
        }
      }
    }
  }
</style>
